import axios from "axios";
import { message } from "antd";
import { getUserToken } from "../until/userToken";
import { error } from "console";

const instance = axios.create({
  timeout: 60 * 1000,
});

instance.interceptors.request.use(
  (config) => {
    config.headers["Authorization"] = `Bearer ${getUserToken()}`;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

instance.interceptors.response.use((res) => {
  const resdata = (res.data || {}) as ResType;
  const { error, data, msg } = resdata;
  if (error !== 0) {
    if (msg) {
      message.error(msg);
      throw new Error(msg);
    }
  }
  return data as any;
});

export default instance;

export interface ResType {
  error: number;
  data?: DataType;
  msg: string;
}

export interface DataType {
  [key: string]: any;
}
